package com.athena.framework.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author likun
 * 2018/6/25 15:21
 **/
public class ProxyFactory implements MethodInterceptor {

    /**
     * 维护目标对象
     */
    private Object bean;

    /**
     * 需要做操作的方法
     */
    private List<Method> methodList;

    /**
     * 切面类实例
     */
    private ProxyInterface aopBean;

    public ProxyFactory(Object bean, List<Method> methodList, ProxyInterface aopBean) {
        this.bean = bean;
        this.methodList = methodList;
        this.aopBean=aopBean;
    }

    /**
     * 给目标对象创建一个代理对象
     * @return
     */
    public Object getProxyInstance(){
        //1.工具类
        Enhancer en = new Enhancer();
        //2.设置父类
        en.setSuperclass(bean.getClass());
        //3.设置回调函数
        en.setCallback(this);
        //4.创建子类(代理对象)
        return en.create();

    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        boolean b=false;
        if (methodList.contains(method)){
            b=true;
        }

        if (b){
            aopBean.before(obj,method,args);
        }

        //执行目标对象的方法
        Object returnValue = method.invoke(bean, args);

        if (b){
            aopBean.after(obj,method,args,returnValue);
        }

        return returnValue;
    }
}
